/**
 * 订单投标记录详情
 */
/**
 * 加载参与人信息
 */
var flowUserSelect = flowUserSelect || {};
flowUserSelect.label = 'flowUser-select-law';
flowUserSelect.dataUrl = '/sc/general/allOrder/flowuser.do';
flowUserSelect.optStr = ''; // 下拉列表数据
var selectCount = 0;
var uploadCount = 0;

$(function(){
    var wordCount = $("#wordCount"),
        textArea = wordCount.find("textarea"),
        word = wordCount.find(".word");
        statInputNum(textArea,word);
});
/*
* 剩余字数统计
* 注意 最大字数只需要在放数字的节点哪里直接写好即可 如：<var class="word">200</var>
*/
function statInputNum(textArea,numItem) {
    var max = numItem.text(),
    curLength;
    textArea[0].setAttribute("maxlength", max);
    curLength = textArea.val().length;
    numItem.text(max - curLength);
    textArea.on('input propertychange', function () {
        numItem.text(max - $(this).val().length);
    });
}
//初始化
flowUserSelect.init = function (selector, callback) {
    if (!this.optStr) {
        $.ajax({
            type: "POST",
            url: sysInfo.basePath + flowUserSelect.dataUrl,
            success: function (result) {
                var $dom = $(selector);
                var productStr = "";
                if ($dom.children().length > 1) {
                    productStr += '<option value="">请选择</option>';
                    $dom.empty();
                }
                if (result) {
                    for (var i = 0; i < result.length; i++) {
                        var item = result[i];
                        var opt = '<option  value="' + item.id + '">' + item.realName + '-' + item.loginName + '</option> ';
                        productStr += opt;
                        flowUserSelect.optStr += opt;
                    }
                }
                $dom.append(productStr);
                if (callback != null && typeof callback == 'function') {
                    callback();
                }
            }
        });
    } else {
        var $dom = $(selector);
        var productStr = "";
        if ($dom.children().length > 1) {
            productStr += '<option>请选择</option>';
            $dom.empty();
        }
        productStr += this.optStr;
        $dom.append(productStr);
        if (callback != null && typeof callback == 'function') {
            callback();
        }
    }
}

var table = null;
$(document).ready(function () {
        table = $('#myTable').dataTableExtend({
            "ajax": {"url": sysInfo.basePath+"/sc/general/bid/queryBidList.do", "type": "post"},
            "fnServerParams": function (aoData) {
                aoData = $.extend(aoData, {scProductOrderId: $('#mainId').val()});
                return aoData;
            },
            "scrollX": "true",//是否开启横项滚动
            "fixedColumns": {//锁定列，只有开启scrollX时才生效
                "leftColumns": 0,
                "rightColumns": 0
            },
            "aoColumns": [
            	 {
                     "orderable": false,
                     "render": function (data, type, full, meta) {
                         return meta.row + 1;
                     }
                 }, {
                    "orderable": false,
                    "data": "bidUserName"
                }, {
                    "orderable": false,
                    "data": "workTime"
                },
                {
                    "orderable": false,
                    "data": "workTimeCost"
                },
                {
                    "orderable": false,
                    "data": "commission"

                },
                {
                    "orderable": false,
                    "data": "allCost"
                },
                {
                    "orderable": false,
                    "data": "contractPercentage",
                    "render": function (data, type, full, meta) {
                    	var money = parseInt($("#money").val());
                    	var cost = parseInt(full.allCost);
                    	if(isNaN(money)){
                    		return "";
                    	}else{
                    		return ((cost/money)*100).toFixed(2)+"%";
                    	}
                    }
                }, 
                {
                    "orderable": false,
                    "data": "joiners",
                    "render": function (data, type, full, meta) {
                    	if(data!=null){
                    		return data.replace(/,/g, '<br/>');
                    	}else{
                    		return data;
                    	}
                    }
                },
                {
                    "orderable": false,
                    "data":"id",
                    "render": function (data, type, full, meta) {
                    	return data;
                    }
                },
                {
                    "orderable": false,
                    "data": "remark",
                    "render": function (data, type, full, meta) {
                    	if(data.length>10){
                    		return '<p title="'+data+'">'+data.substring(0,9)+"......"+'</p>';
                    	}
                    	else{
                    		return data?data:"";
                    	}
                    }
                },
                {
                    "orderable": false,
                    "data": "status",
                    "render": function (data, type, full, meta) {
                    	if(data==1){
                    		return "已中标";
                    	}else{
                    		return "未中标";
                    	}
                    }
                },
                {
                    "orderable": false,
                    "data": "createTime"
                }],
            "columnDefs": [{
                targets: [4], //第1，2，3列
                createdCell: function (td, cellData, rowData, row, col) {
                    var nodeSt = rowData.nodeultratime;
                    var orderSt = rowData.productultratime;
                    if (nodeSt == "OVERDUE_STATE2") {
                        $(td).parent().addClass(" bgOver")
                    }
                    if (orderSt == "OVERDUE_STATE2") {
                        $(td).parent().removeClass("bgOver").addClass(" bgRed")
                    }
                }
            },{
            	targets: [8], //第1，2，3列
                createdCell: function (td, cellData, rowData, row, col) {
                	var $td = $(td), id = $td.text();
                	$td.empty().append(getUploadLab(id));
                }
            }]
        });
        /**
         * 
         * @returns
         */
        var dggUploader = $(".upload").dggUploader({
            fileId: $("#bidFieldId").val()//文件ID
            , uploadBaseUrl: uploadBaseUrl
            ,isRemove:false
            , showIcon: true
        }).findFiles($("#bidFieldId").val(), "bidFilePreview", 0, 0);//获取文件列表
        
        
        var dggUploader2 = $(".upload-bjzl").dggUploader({
            fileId: $("#bidFileIdBjzl").val()//文件ID
            , uploadBaseUrl: uploadBaseUrl
            , showIcon: true
        });
        //dggUploader2.findFiles($("#bidFieldIdBjzl").val(), "bidFilePreviewBjzl", 0, 0);
       
        /*
         * 动态添加参与人输入框
         */
        $("#add-icon").on("click",function(){
        	selectCount++;
        	var str;
        	str = "<li class='partyList joinLi'>"
                      +"<select class='select-style' name='joinerName_' flowUser-select-law selectCount="+selectCount+">"
                      	+"<option value>请选择</option>"
                      +"</select>"
                      +"<span class='partyItem'>&nbsp;工时成本占比&nbsp;"
                      	+"<label class='input-unit'>"
        	              	+"<input maxlength='7' type='text' class='input-style cost-percent' name='workTimeCostPercent_' style='height:24px'>"
        	              	+"<span class='unit'>%</span>"
                        +"</label>"
                      +"</span>";
                      var tc = "<span class='partyItem tc'>&nbsp;提成金额&nbsp;"
                     	+"<label class='input-unit'>"
                     		+"<input maxlength='7' type='text' class='input-style commission-item' name='commission_' style='height:24px'>"
                            +"<span class='unit'>元</span>"
                        +"</label>"
                      +"</span>";
                      if($("input[type='radio']:checked").val()=="承包人"){
                    	  tc = "<span class='partyItem tc' style='display:none'>&nbsp;提成金额&nbsp;"
                           	+"<label class='input-unit'>"
                           		+"<input maxlength='7' type='text' class='input-style commission-item' name='commission_' style='height:24px'>"
                                  +"<span class='unit'>元</span>"
                              +"</label>"
                            +"</span>";
                      }
                      var end = "<a onclick='cancel(this)' href='javascript:;' ><i class='layui-icon' style='cursor: pointer;color:#FF5722;margin-left: 10px;font-size:14px'>删除</i> </a>"
                  +"</li>";
                      str = str + tc +end;
        	$("#joiner").append(str);
        	/**
             * 动态初始化参与人
             * @returns
             */
            var label = flowUserSelect.label;
            var $dom = $('select[' + label + '][selectCount='+selectCount+']');
            flowUserSelect.init($dom, function () {
                $dom.attr(label, 'true');
                $dom.attr('class', 'select-style');
                $dom.attr('style', 'border-radius:0px');
                $dom.select2({
                    placeholder: "请选择",
                    width: "16%",
                    height:"30px",
                    language: "zh-CN",
                    allowClear: true
                });
            });
        })
        /**
         * 动态初始化参与人
         * @returns
         */
        var label = flowUserSelect.label;
        var $dom = $('select[' + label + ']');
        flowUserSelect.init($dom, function () {
            $dom.attr(label, 'true');
            $dom.select2({
                placeholder: "请选择",
                width: "16%",
                height:"30px",
                language: "zh-CN",
                allowClear: true
            });
        });
        /**
         * 验证
         */
        //验证工时
        $('#workTime').on('blur',function(){
        	var regu = /^[1-9]\d*$/;
        	var val = $('#workTime').val();
        	if(val!=""){
        		if (!regu.test(val)) {
        	          $(this).val("");
        	          DGG.layer.msg("工时只能为正整数",{icon: '2'});
        	        } 
        	}
        });
      //验证工时成本
        $('#workTimeCost').on('blur',function(){
        	var regu = /^[0-9]+\.?[0-9]{0,9}$/;
        	var val = $('#workTimeCost').val();
        	if(val!=""){
        		if (!regu.test(val)) {
        	          $(this).val("");
        	          DGG.layer.msg("工时成本只能为正数金额",{icon: '2'});
        	        } else{
        	        	$(this).val(parseFloat(val).toFixed(2));
        	        }
        	}
        });
        //验证参与人提成金额
        $("body").on("blur",'.commission-item',function(){
        	var regu = /^[0-9]+\.?[0-9]{0,9}$/;
        	var val = $(this).val();
        	if(val!=""){
        		if (!regu.test(val)) {
        	          $(this).val("");
        	          DGG.layer.msg("工时成本只能为正数金额",{icon: '2'});
        	        } else{
        	        	$(this).val(parseFloat(val).toFixed(2));
        	        	//自动计算总提成
        	        	var commissionItems = $(".commission-item");
        	        	var commission = 0;
        	        	for(var i = 0;i<commissionItems.length;i++){
        	        		var v =commissionItems[i].value;
        	        		if(v!=null&&v!=''){
        	        			commission += parseFloat(v);
        	        		}
        	        	}
        	        	$("#commission").val(parseFloat(commission).toFixed(2));
        	        	var workTime = $('#workTime').val(), workTimeCost = $('#workTimeCost').val();
        	        	if(workTime!=''&&workTime!=null&&workTimeCost!=null&&workTimeCost!=''){
        	        		var allCost = parseFloat(workTime*workTimeCost)+parseFloat(commission);
        	    			$("#allCost").val(parseFloat(allCost).toFixed(2));
        	        		}
        	        	}
        	        }
        })
        
        //验证参与人工时成本占比
        $("body").on("blur",'.cost-percent',function(){
        	var regu = /^([1-9]\d?|100)$/;
        	var val = $(this).val();
        	if(val!=""){
        		if (!regu.test(val)) {
        	          $(this).val("");
        	          DGG.layer.msg("工时成本占比只能为1~100",{icon: '2'});
        	          return false;
        	        } else{
        	        	$(this).val(val);
        	        }
        		//验证累积百分比是否大于100
        		var costPercents = $(".cost-percent");
        		var cost = 0;
        		for(var i=0;i<costPercents.length;i++){
        			if(costPercents[i].value!=''){
        				cost+=parseInt(costPercents[i].value);
        			}
        		}
        		if(cost>100){
        			$(this).val("");
      	            DGG.layer.msg("工时成本占比总计不能大于100%",{icon: '2'});
        		}else{
        			$(this).val(val);
        		}
        	}
        })
/**
 * 自动计算总报价:
 */
$('#workTime,#workTimeCost').on("blur",function(){
	var workTime = $('#workTime').val(), workTimeCost = $('#workTimeCost').val();
	if($("input[type='radio']:checked").val()=="承包人"){
		if(workTime!=""&&workTimeCost!=""){
			var allCost = workTime*workTimeCost;
			$("#allCost").val(parseFloat(allCost).toFixed(2));
		}else{
			$("#allCost").val('');
		}
	}else if($("input[type='radio']:checked").val()=="人单"){
		var commission = $('#commission').val();
		if(workTime!=""&&workTimeCost!=""&&commission!=""){
			var allCost = parseFloat(workTime*workTimeCost)+parseFloat(commission);
			$("#allCost").val(parseFloat(allCost).toFixed(2));
		}else{
			$("#allCost").val('');
		}
}
})
})
/*
 * 删除当前节点
 */
function cancel(e){
	$(e).parent().remove();
	//自动计算总提成
	var commissionItems = $(".commission-item");
	var commission = 0;
	for(var i = 0;i<commissionItems.length;i++){
		var v =commissionItems[i].value;
		if(v!=null&&v!=''){
			commission += parseFloat(v);
		}
	}
	$("#commission").val(parseFloat(commission).toFixed(2));
	var workTime = $('#workTime').val(), workTimeCost = $('#workTimeCost').val();
	if(workTime!=''&&workTime!=null&&workTimeCost!=null&&workTimeCost!=''){
		var allCost = parseFloat(workTime*workTimeCost)+parseFloat(commission);
		$("#allCost").val(parseFloat(allCost).toFixed(2));
		}
	selectCount--;
}
/*
 * 退出弹出层
 */
function closeLayer(){
	window.parent.dataTableReload();
    parent.layer.closeAll();
}

/**
*表单提交
*/
function saveForm(){
	/**
	 * 表单字段验证
	 */
	var workTime = $("#workTime").val(),
	workTimeCost = $("#workTimeCost").val(),
	commission = $("#commission").val();
	if(null==workTime||""==workTime){
		DGG.layer.msg("工时不能为空",{icon: '2'});
		//layer.closeAll();
		return false;
	}
	if(null==workTimeCost||""==workTimeCost){
		DGG.layer.msg("工时成本不能为空",{icon: '2'});
		//layer.closeAll();
		return false;
	}
	if($("input[type='radio']:checked").val()=="人单"){
		if(null==commission||""==commission){
			DGG.layer.msg("请至少填写一个参与人完整信息",{icon: '2'});
			layer.closeAll();
			return false;
		}
	}
	DGG.Layer.loading.start();
	var data = $("#data-form").serialize();
	var joiners = $(".joinLi");
	var joinerId="",joinerName = "",workTimeCostPercent="",commission="";
	for(var i=0;i<joiners.length;i++){
		joinerId += $(joiners[i]).find('select').val()==""?null+",":($(joiners[i]).find('select').val()+",");
		joinerName += $(joiners[i]).find('select option:selected').text()==""?null+",":($(joiners[i]).find('select option:selected').text()+",");
		workTimeCostPercent += $(joiners[i]).find('input[name="workTimeCostPercent_"]').val()==""?null+",":($(joiners[i]).find('input[name="workTimeCostPercent_"]').val()+",");
		commission += $(joiners[i]).find('input[name="commission_"]').val()==""?null+",":($(joiners[i]).find('input[name="commission_"]').val()+",");
	}
	$.ajax({
        url: sysInfo.basePath + '/sc/general/bid/saveBidRecord.do?scProductOrderId='+$("#mainId").val()+"&"+data,
        data: {
        	"joinerIds":joinerId,
        	"joinerNames":joinerName,
        	"workTimeCostPercents":workTimeCostPercent,
        	"commissions":commission
        },
        type: "POST",
        dataType: "json",
        success: function (obj) {
        	DGG.Layer.loading.done();
            if (obj.code != 0) {
                DGG.Layer.loading.done();
                DGG.Layer.message(obj.msg, {icon: '2'}, function () {
                	return false;
                    //window.parent.dataTableReload();
                });
            } else {
                DGG.Layer.message('操作成功！', {icon: '1'}, function () {
                    window.parent.dataTableReload();
                    parent.layer.closeAll();
                });
            }
        }
    });
}

function getUploadLab(id){
	var str ="";
	str='<div class="upload-bz" style="display:inline">'
    +'<input type="hidden" name="fileId" value="sccenter_general_'+id+'_scbidrecord_bid_bidFileId" id="bidFieldId'+id+'">'
    +'<ul class="data-warp" id="bidFilePreview'+id+'" style="display:inline">'
       +'<li class="upload-re">'
            +'<a href="javascript:void(0)" class="upload-button upload"></a>'
            +'<p>上传附件</p>'
        +'</li>'
    +'</ul>'
    +'</div>';
	var $upload = $(str);
	$upload.find('.upload').dggUploader({
        fileId: $upload.find('input[name="fileId"]').val(),//文件ID
        uploadBaseUrl: uploadBaseUrl,
        isRemove:false,
        showIcon: true
    }).findFiles($upload.find('input[name="fileId"]').val(), 'bidFilePreview' + id, 0, 0);
	$upload.find("li[class='upload-re']").remove();
    return $upload[0];
}

